<template>
  <div>
    <img :src="image" alt="" ref="img" class="vanImg" />
    <van-nav-bar
      class="van-nav-bar"
      left-text="取消"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  name: 'EditPhoto',
  props: {
    file: {
      type: File,
      required: true,
      cropper: null
    }
  },
  data () {
    return {
      image: window.URL.createObjectURL(this.file)
    }
  },
  methods: {
    // 得到裁切后的图片 因为原有的 cropperjs 不支持promise 封装为一个 promise 对象
    getCroppedCanvas () {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          resolve(blob)
        })
      })
    },
    async onConfirm () {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true,
        duration: 0
      })

      // 当使用 cropperjs 时候
      const file = await this.getCroppedCanvas()
      const fd = new FormData()
      fd.append('photo', file)

      // Content-Type multipart/form-data 接口文档要求
      // 故请求体不再是 {}形式的 body 对象，而是一个 formdata 对象
      // const fd = new FormData()
      // fd.append('photo', this.file)
      const { data: res } = await this.$https.patch('/app/v1_0/user/photo', fd)
      console.log(res.data.photo)
      this.$emit('success', res.data.photo)
      this.$emit('close')
      this.$toast.success('修改成功！')
    }
  },
  mounted () {
    // 配置裁切 cropperjs
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  }
}
</script>

<style scoped lang="less">
.vanImg {
  display: block;
  max-width: 100%;
}
.van-nav-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
  /deep/.van-nav-bar__text {
    color: #fff;
  }
}
</style>
